package com.auerdi.ui.detail.cutprice.child;

import android.content.Context;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.auerdi.GlideApp;
import com.auerdi.R;
import com.auerdi.ui.detail.ADProductDetailFragment;
import com.auerdi.ui.detail.ADProductWebviewFragment;
import com.auerdi.ui.detail.cutprice.detail.ADCutProductDetailFragmentM;
import com.example.egghttp.EggLog.L;
import com.example.egghttp.RetrofitClient;
import com.example.egghttp.retrofit.AdService;
import com.example.egghttp.retrofit.beans.BOb;
import com.example.egghttp.retrofit.beans.banner.BannerList;
import com.example.egghttp.retrofit.beans.banner.GoodCutList;
import com.example.egghttp.retrofit.beans.banner.HomeBanner;
import com.example.egghttp.retrofit.beans.goods.CutProduct;
import com.example.egghttp.retrofit.beans.goods.Product;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.yokeyword.fragmentation.SupportFragment;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by YoKeyword on 16/2/14.
 */
public class ADCutChildLieft extends SupportFragment {

    Unbinder unbinder;
    @BindView(R.id.recy)
    RecyclerView recy;
    @BindView(R.id.banner)
    Banner banner;
    private List<CutProduct> mProLists = new ArrayList<>();


    public static ADCutChildLieft newInstance() {

        Bundle args = new Bundle();

        ADCutChildLieft fragment = new ADCutChildLieft();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ad_cut_child_a, container, false);
        unbinder = ButterKnife.bind(this, view);


        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        RetrofitClient.getPDAClient().create(AdService.class).bargainLists()               //获取Observable对象
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<GoodCutList>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BOb<GoodCutList> goodCutListBOb) {
                        List<CutProduct> goodLists = goodCutListBOb.getBody().getGoodLists();
                        mProLists.clear();
                        mProLists.addAll(goodLists);
//                        mProLists.addAll(mProLists);
//                        mProLists.addAll(mProLists);
                        recy.getAdapter().notifyDataSetChanged();
                    }
                });

        RetrofitClient.getClient().create(AdService.class).homebanner("", "")
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<BannerList>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BOb<BannerList> bannerListBOb) {
                        List<HomeBanner> banners = bannerListBOb.getBody().getHomeBanner_list();
                        banner.setImageLoader(new ImageLoader() {
                            @Override
                            public void displayImage(Context context, Object path, ImageView imageView) {
                                HomeBanner banner = (HomeBanner) path;


                                GlideApp.with(getActivity())
                                        .load(banner.getImg())
                                        .placeholder(R.mipmap.logo)
                                        .error(R.mipmap.pay_err)
                                        .fitCenter()
                                        .into(imageView);

                                imageView.setOnClickListener(v -> {

                                    L.d("hcia", "banner.getUrl():" + banner.getUrl());


                                    Observable.just(banner.getUrl())
                                            .map(s -> Uri.parse(s))
                                            .map(uri -> uri.getQuery().split("/"))
                                            .doOnNext(strings -> {
                                                String productId = strings[4];
                                                String tid = strings[6].split("\\.")[0];
                                            })

                                            .subscribe(new Subscriber<String[]>() {
                                                @Override
                                                public void onCompleted() {
                                                    L.d("hcia", "onCompleted:");

                                                }

                                                @Override
                                                public void onError(Throwable e) {
                                                    L.d("hcia", "e:" + e);
                                                    EventBus.getDefault().post(ADProductWebviewFragment.newInstance(banner));

                                                }

                                                @Override
                                                public void onNext(String[] strings) {
                                                    L.d("hcia", "strings:" + strings.length);
                                                    String productId = strings[4];
                                                    String tid = strings[6].split("\\.")[0];

                                                    Product product = new Product();
                                                    product.setId(productId);
                                                    product.setHuodongType(tid);
                                                    EventBus.getDefault().post(ADProductDetailFragment.newInstance(product));

                                                }
                                            });


                                });


                            }
                        });

                        banner.setImages(banners);
                        banner.start();


                    }
                });

    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        recy.setNestedScrollingEnabled(false);
        recy.setLayoutManager(new GridLayoutManager(getActivity(), 1) {

            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        recy.setAdapter(new CommonAdapter<CutProduct>(_mActivity, R.layout.item_cut_world, mProLists) {
            @Override
            protected void convert(ViewHolder viewHolder, final CutProduct item, int position) {

                ImageView imgView = viewHolder.getView(R.id.img);
                ImageView gPic = viewHolder.getView(R.id.gpic);
                viewHolder.setText(R.id.title, item.getGoods_name());
                viewHolder.setText(R.id.gname, item.getProduct_country_name());
                viewHolder.setText(R.id.stitle, item.getShort_title());
                viewHolder.setText(R.id.num, "剩" + item.getSurplus_sum() + "份 已有" + item.getNumber_participants() + "人参加");


                viewHolder.setText(R.id.apri, "¥" + item.getFloor_price());
                viewHolder.setText(R.id.bpri, "¥" + item.getMarket_price());
                TextView bb = viewHolder.getView(R.id.bpri);
                bb.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 设置中划线并加清晰

                Picasso.get().load(item.getCover_img_url()).error(R.mipmap.logo).placeholder(R.mipmap.logo).fit().into(imgView);
                Picasso.get().load(item.getProduct_country_logo()).error(R.mipmap.epta).placeholder(R.mipmap.epta).fit().centerInside().into(gPic);

                viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

//                        EventBusActivityScope.getDefault((Activity) viewHolder.getConvertView().getContext()).post(ADCutProductDetailFragment.newInstance(item));
//                        EventBus.getDefault().post(ADCutProductDetailFragment.newInstance(item));
                        EventBus.getDefault().post(ADCutProductDetailFragmentM.newInstance(item));


                    }
                });
            }
        });

    }


    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


}
